package com.edu.project.http;



import com.edu.project.App;
import com.edu.project.http.interfaces.Api;

import java.io.File;
import java.util.concurrent.TimeUnit;

import okhttp3.Cache;
import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Created by sheng on 2016/11/4.
 */
public class HttpClient {

    private static Api mApi;

    private static OkHttpClient mOkHttpClient;

    private static final String URL = "http://www.weather.com.cn/";


    public static void init() {
        if (mApi == null) {
            synchronized (HttpClient.class) {
                if (mApi == null) {
                    initOkHttpClient();
                    Retrofit retrofit = new Retrofit.Builder()
                            .client(mOkHttpClient)
                            .addConverterFactory(GsonConverterFactory.create())// json 转换器
                            .addCallAdapterFactory(RxJavaCallAdapterFactory.create())// RxJava 适配器
                            .baseUrl(URL)
                            .build();

                    mApi = retrofit.create(Api.class);

                }
            }
        }

    }


    private static void initOkHttpClient() {
        if (mOkHttpClient == null) {

            File cacheFile = new File(App.context().getCacheDir(), "Cache"); // 指定缓存路径
            Cache cache = new Cache(cacheFile, 1024 * 1024 * 10); // 指定缓存大小10Mb

            HttpLoggingInterceptor interceptor = new HttpLoggingInterceptor();
            interceptor.setLevel(HttpLoggingInterceptor.Level.BODY);

            mOkHttpClient = new OkHttpClient.Builder()
                    .cache(cache)
                    .addInterceptor(interceptor)
                    .retryOnConnectionFailure(true)
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .build();
        }
    }


    public static Api getmApi() {
        return mApi;
    }
}
